package sipus.database.hibernate;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EntityMode;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.def.DefaultSaveEventListener;
import org.hibernate.metadata.ClassMetadata;

import sipus.common.CommonPrivilages;
import sipus.database.model.AccessedUsers;
import sipus.database.model.DetailLogLogin;
import sipus.database.model.LogUserActifity;


public class SaveEventListener extends DefaultSaveEventListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8669099681437568970L;

	@Override
	public void onSaveOrUpdate(SaveOrUpdateEvent arg0) {
		Serializable serializable = (Serializable) arg0.getObject();
		try {
			if (!(serializable instanceof org.hibernate.envers.DefaultRevisionEntity)) {
				ClassMetadata metadata = HibernateUtil
						.getClassMetadata(serializable.getClass());
				if (metadata != null) {

					metadata.setPropertyValue(
							serializable,
							"oleh",
							sipus.common.Common.getCurrentUser() == null ? "external_update"
									: sipus.common.Common.getCurrentUser()
											.getUserNama(), EntityMode.POJO);
					metadata.setPropertyValue(serializable, "tanggal_dirubah",
							new Date(), EntityMode.POJO);
				}
			}
		} catch (Exception e) {
			System.out.println("serializable = " + serializable.getClass());
			e.printStackTrace();
		}

		super.onSaveOrUpdate(arg0);
		try {
			if (serializable != null
					&& !(serializable instanceof AccessedUsers)
					&& !(serializable instanceof DetailLogLogin)
					&& !(serializable instanceof LogUserActifity)) {
				@SuppressWarnings("rawtypes")
				Class myClass = null;
				try {
					throw new Exception("Who called me?");
				} catch (Exception e) {
					try {
						StackTraceElement[] elements = e.getStackTrace();
						for (StackTraceElement element : elements) {
							if (element.getClassName().startsWith(
									"sipus.action.master")
									&& element.getMethodName().toLowerCase()
											.contains("save")) {
								myClass = Class.forName(element.getClassName());
								break;
							}
						}
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				if (myClass != null) {
					System.out.println("============= save for "
							+ serializable.getClass().getName()
							+ ", this method called from " + myClass.getName()
							+ " ===================");
					CommonPrivilages.saveActivity(myClass,
							CommonPrivilages.CREATE, serializable, "");

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
